import mapboxgl from 'mapbox-gl';
import type React from 'react';
import { memo, useContext, useEffect } from 'react';
import { MapContext } from '../../MapContext';
import styles from './index.module.less';

// 定义 MapboxPopupProps 类型
type MapboxPopupProps = {
  children?: React.ReactNode;
  lngLat: mapboxgl.LngLatLike;
};

const MapboxPopup: React.FC<MapboxPopupProps> = ({ children, lngLat }) => {
  const { mapless, isMapReady } = useContext(MapContext);

  useEffect(() => {
    if (!mapless?.map || !isMapReady) return;

    // 安全地使用mapless实例创建Popup
    const popup = new mapboxgl.Popup({
      closeOnMove: false,
      closeOnClick: false,
      className: styles['react-popup'],
      focusAfterOpen: false,
    })
      .setLngLat(lngLat)
      .addTo(mapless.map)
      .setHTML('<p>Hello, Mapbox!</p>');

    return () => {
      popup.remove();
    };
  }, [mapless, isMapReady, lngLat]);

  useEffect(() => {
    console.log('mapless');
  }, [mapless]);

  useEffect(() => {
    console.log('isMapReady');
  }, [isMapReady]);

  useEffect(() => {
    console.log('lngLat');
  }, [lngLat]);

  return children;
};

function isEqual(
  prev: Readonly<MapboxPopupProps>,
  next: Readonly<MapboxPopupProps>,
): boolean {
  return (
    JSON.stringify(prev.lngLat) === JSON.stringify(next.lngLat) &&
    prev.children === next.children
  );
}

export default memo(MapboxPopup, isEqual);
